<?php
/*加上全返的功能*/
class RangeCashbackleveltest{
	public $money;
	public $order;
	public $site_id;
	public $userlist;
	public $orderdb;
	public $memberdb;
	public $member_id;
	public $error = array();
	//构造函数
	public function RangeCashbackleveltest($order_id = 0, $site_id = 0, $member_id = 0){
		import("@.ORG.Cashback.Cashback");
		$this->memberdb = D('Member');
		$this->orderdb = D('Order');
		$this->saledb = M('Sale');
		$this->money = $this->getmoney();
		$this->site_id = $site_id;
		
		$db = M('Affiliatesetting');
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'RangeCashbackleveltest')) -> find();
		$this -> affsettingarr = unserialize($affsetting['value']);
		
		$this->order = $this->orderdb -> where(array('id' => $order_id)) -> find();
		
		$this->member_id = $member_id > 0? $member_id: $this->order['member_id'];
		if(!$this->order){
			$this->error['info'] = '订单不存在！';
		}
		if($this->order['status'] ==2){
		     $this->setCashback();
		}
		$this->updateUserLevel();
	}
	//创建设置项表单
	public function createform(){
		
		$db = M('Affiliatesetting');
		
		$ret = array ('levelname' => array ( 0 => '股东商', 1 => '渠道商', 2 => '代理商', 3 => '分销商', ), 'levelbuy' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'levelaff' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'levelaff_' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'rlevel' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ),'level' => array ( 0,0,0,0,0,0,0,0 ),'levelnamebase' => 'VIP会员', 'changelevel' => '恭喜您升级成为：@levelname@');
		
		
		
		$ret = $db -> where(array('site_id' => $this->site_id,'classname' => 'RangeCashbackleveltest')) -> find();
		$ret = unserialize($ret['value']);
		//F('ret',$ret);
		$html = '<style>#RangeCashbackleveltest td{padding:5px;}</style><table id="RangeCashbackleveltest" border="1" cellspacing="0" cellpadding="5" width="100%">
  <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
	<th align="center" style="text-align:center;">级别名称</th>
	<th align="center" style="text-align:center;">最低消费</th>
	<th align="center" style="text-align:center;">直推人数</th> 
	<th align="center" style="text-align:center;">发展人数</th>
    <th align="center" style="text-align:center;">分成比例</th>
  </tr>
  <tr>
    <td align="center" valign="middle">1</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][0].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][0].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][0].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff_[]" value="'.$ret['levelaff_'][0].'" /></td>
    <td align="center"><input type="text" name="rlevel[]" value="'.$ret['rlevel'][0].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">2</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][1].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][1].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][1].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff_[]" value="'.$ret['levelaff_'][1].'" /></td>
    <td align="center"><input type="text" name="rlevel[]" value="'.$ret['rlevel'][1].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">3</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][2].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][2].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][2].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff_[]" value="'.$ret['levelaff_'][2].'" /></td>
    <td align="center"><input type="text" name="rlevel[]" value="'.$ret['rlevel'][2].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">4</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][3].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][3].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][3].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff_[]" value="'.$ret['levelaff_'][3].'" /></td>
    <td align="center"><input type="text" name="rlevel[]" value="'.$ret['rlevel'][3].'" />%</td>
  </tr>
  
</table>
<br>

<table cellpadding="0" class="Threelevel" cellspacing="0" border="1" width="100%">
<tr>
    <td align="center" valign="middle" style="width:150px;">分销资格等级名称</td>
    <td align="left" colspan="2"><input type="text" name="levelnamebase" value="'.$ret['levelnamebase'].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle" style="width:150px;">会员升级后通知信息</td>
    <td align="left" colspan="2"><input style="width:100%" type="text" name="changelevel" value="'.$ret['changelevel'].'" /><br>
等级名称@levelname@
</td>
  </tr>
  
  
  <tr>
    <td align="center" valign="middle" style="width:150px;">分销资格最低消费</td>
    <td align="left" colspan="2"><input type="text" name="levelmoney" value="'.$ret['levelmoney'].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle" style="width:150px;">会员消费提点（1启用，0禁用）</td>
    <td align="left" colspan="2"><input type="text" name="VIPaff" value="'.$ret['VIPaff'].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle" style="width:150px;">推荐人返现百分比</td>
    <td align="left" colspan="2"><input type="text" name="cashbackaff" value="'.$ret['cashbackaff'].'" />%（<span style="color:#f00">每天返：返现总额=商品总额*当前百分比</span>）这里指被推荐人购买返现商品后，返现商品总额小于推荐人返现商品总额时，推荐人对当前订单的返现商品的返现额度百分比.实际返现商品的配置中返现总额请填写0</td>
  </tr>
  
  
  <tr>
    <td align="center" valign="middle" style="width:150px;">购买人返现百分比</td>
    <td align="left" colspan="2"><input type="text" name="cashbackself" value="'.$ret['cashbackself'].'" />%（<span style="color:#f00;">每天返：返现总额=商品总额*当前百分比</span>）这里指被推荐人购买返现商品后对当前订单的返现商品的返现额度百分比。实际返现商品的配置中返现总额请填写0</td>
  </tr>
   <tr>
    <td align="center" valign="middle" style="width:150px;">返现总天数</td>
    <td align="left" colspan="2"><input type="text" name="cashbackdate" value="'.$ret['cashbackdate'].'" />总共返多少天</td>
  </tr>
</table>
<br>

<style>.Threelevel td{padding:5px;}</style><table class="Threelevel" border="1" cellspacing="0" cellpadding="5" width="100%">
  <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
    <th align="center" style="text-align:center;">分成比例</th>
	 
  </tr>
  
  <tr>
    <td align="center" valign="middle">1</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][0].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">2</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][1].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">3</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][2].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">4</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][3].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">5</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][4].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">6</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][5].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">7</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][6].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">8</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][7].'" />%</td>
	
  </tr>
</table>
';

        return $html;
	}
	
	//返回当前会员的返现商品总额
	public function getcashbackselftotal($sale = array()){
		$product_sql = M('Cashback_config') -> where(array('site_id' => __SITEID__, 'total' => 0)) -> Field('product_id') -> buildSql();
		return $this->saledb -> where("product_id in(".$product_sql.") and member_id = '".$this->member_id."' and pay_status = 1") -> sum('total');
	}
	//返回推荐人的返现商品总额
	public function getcashbackafftotal($sale = array()){
		$member_id = M('Member') -> where(array('id' => $this->member_id)) -> getField('pid');
		$product_sql = M('Cashback_config') -> where(array('site_id' => __SITEID__, 'total' => 0)) -> Field('product_id') -> buildSql();
		return $this->saledb -> where("product_id in(".$product_sql.") and member_id = '".$member_id."' and pay_status = 1") -> sum('total');
	}
	//设置一个商品的当前会员和上家会员的实际返现总额度
	//sale为商品销售一条记录
	public function setcashbacktotal($sale){
		$Cashback_countbdb = M('Cashback_countb');
		//if($sale['pay_status'] == 0){return false;}
		$ret = array();
	    //查找该商品，确认是否为返现商品，并且配置返现总金额为零，因为这里不能和原来返现冲突，返现总额=当前商品总额*返现百分比
		$product = M('Cashback_config') -> where(array('product_id' => $sale['product_id'], 'total' => 0)) -> find();
		if(!$product){
			return false;
		}else{
			//设置当前会员的返现总额
			$sale['member_id'] = $this->member_id;
			$Cashback = new Cashback($sale);
			$Cashback->config['status'] = 1;
			$Cashback->config['total'] = $this -> affsettingarr['cashbackdate']*$sale['total'] * $this -> affsettingarr['cashbackself']/100;
			$Cashback->config['rate'] = (1/$this -> affsettingarr['cashbackdate'])*10000;
			if($Cashback->canCashback()) {
				// 增加返现总额、余额操作
				$Cashback->addMoney();
			}
			
			
			
			//设置推荐人的返现总额
			$sale['member_id'] = M('Member') -> where(array('id' => $this->member_id)) -> getField('pid');
			if($sale['member_id'] > 0){
				$Cashback = new Cashback($sale);
				$Cashback->config['status'] = 1;
				//找到推荐人
				$getcashbackselftotal = $this -> getcashbackselftotal($sale);
				$getcashbackafftotal = $this -> getcashbackafftotal($sale);
				if($getcashbackselftotal > $getcashbackafftotal){
					//$last_money = M('Sale') -> where(array('member_id' => $sale['member_id'])) -> order('id desc') -> getField('total');
					//dump($last_money);
					//父级比当前小，扣除一部分保存起来
					
					//$last_money[] = $sale['total'];
					
					$savemoney = $getcashbackselftotal - $getcashbackafftotal;
					
					
					
					//$Cashback_countbdb = M('Cashback_countb');
					$savemoney_ = $Cashback_countbdb -> where(array('smemberid' => $this->member_id, 'member_id' => $sale['member_id'])) -> find();
					if($savemoney_){
						$Cashback_countbdb -> where(array('smemberid' => $this->member_id, 'member_id' => $sale['member_id'])) -> setInc('money', $savemoney);
					}else{
						$Cashback_countbdb -> add(array('smemberid' => $this->member_id,'money' => $savemoney, 'member_id' => $sale['member_id']));
					}
					//查找上次被保存起来的返现金额加回去
					
					
					if($sale['total'] - $savemoney < 0){
						$Cashback->config['status'] = 0;
					}
					
					
					
					
					$Cashback->config['total'] = $this -> affsettingarr['cashbackdate']*($sale['total'] - $savemoney) * $this -> affsettingarr['cashbackaff']/100;
					$Cashback->config['rate'] = (1/$this -> affsettingarr['cashbackdate'])*10000;
				}else{
					/*$Cashback->config['total'] = $this -> affsettingarr['cashbackdate']*$sale['total'] * $this -> affsettingarr['cashbackaff']/100;
					$Cashback->config['rate'] = (1/$this -> affsettingarr['cashbackdate'])*10000;*/
				}
				
				if($Cashback->canCashback()) {
					// 增加返现总额、余额操作
					$Cashback->addMoney();
				}
			}
			
			$savemoney_ = $Cashback_countbdb -> where(array('member_id' => $this->member_id)) -> find();
			//返回被保存的返现金额
			if($savemoney_['money'] > 0){//dump($savemoney_);
				$Cashback->config['status'] = 1;
				$sale['member_id'] = $this->member_id;
				$minmoney[] = $savemoney_;
				$minmoney[] = $sale['total'];
				$Cashback->config['total'] = $this -> affsettingarr['cashbackdate']*min($minmoney) * $this -> affsettingarr['cashbackaff']/100;
				//dump($Cashback->config['total']);
				if($Cashback->config['total'] > 0){
					$Cashback->config['rate'] = (1/$this -> affsettingarr['cashbackdate'])*10000;
					$Cashback_countbdb -> where(array('member_id' => $sale['member_id'])) -> setDec('money', min($minmoney));
					$Cashback->config['status'] = 1;
				}else{
					$Cashback->config['status'] = 0;
				}
				if($Cashback->canCashback()) {
					// 增加返现总额、余额操作
					$Cashback->addMoney();
				}
			}
			
			
			
		}
		return true;
	}
	//写入所有商品的返现
	function setCashback(){
		$list = $this->getmoney();
		foreach($list as $v){
			$this->setcashbacktotal($v);
		}
	}
	//保存设置项
	public function saveform(){
		if(isset($_POST['level'])){
			$data['classname'] = 'RangeCashbackleveltest';
			$data['value'] = serialize($_POST);
			$data['site_id'] = $this->site_id;
			$db = M('Affiliatesetting');
			$pc = (float)$_POST['rlevel'][0];
			foreach($_POST['level'] as $v){
				$pc += (float)$v;
			}
			if($pc > 100){
				$this->error['info'] = '设置错误，分成比的和大于100！';
				return false;
			}
			//dump($data);
			$ret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> find();
			if($ret){
				$saveret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> data(array('value' => $data['value'])) -> save();
			}else{
				$saveret = $db -> data($data) -> add();
			}
			if($saveret){
				return true; 
			}else{
				$this->error['info'] = $db -> getLastSql();
				return false;
			}
			
		}
	}
	
	
	public function updateUserLevel(){
		$db = M('Affiliatesetting');
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'RangeCashbackleveltest')) -> find();
		$affsettingarr = unserialize($affsetting['value']);
		//查询用户
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		//升级为基本分销等级
		$rlevel = array(0,0,0);
		$total = (float)$this->orderdb -> where(array('member_id' => $this->member_id, 'status' => 2)) -> sum('total');
		$mylevel = 0;
		if($affsettingarr['levelmoney'] <= $total){
		    //更新用户等级
			$mylevel = 1;
	    }
		//升级为其它等级
		//计算直推人数
		$affCount = $this->memberdb -> getLevel1Count($memberInfo['id'], 1, 1);
		//计算八级以内市场人数
		$affCount_ = $this->memberdb -> getLevel1Count($memberInfo['id'], 1, 8);
		//开始升级
		
		foreach(array_reverse($affsettingarr['levelbuy']) as $k => $v){
			if($total >= $v){
				$rlevel[0] = $k + 2;
			}
		}
		foreach(array_reverse($affsettingarr['levelaff']) as $k => $v){
			if($affCount >= $v){
				$rlevel[1] = $k + 2;
			}
		}
		
		
		foreach(array_reverse($affsettingarr['levelaff_']) as $k => $v){
			if($affCount_ >= $v){
				$rlevel[2] = $k + 2;
			}
		}
		//dump($rlevel);
		$retlevel = min($rlevel);
		$data['level'] = $retlevel > 0? $retlevel : $mylevel;
		
		//dump($data);
		//if($memberInfo['level'] < $data['level']){
			//如果强制不降级就取消
			
			if($data['level'] < $memberInfo['level'] && $memberInfo['leveldown'] == 0){
				$data['level'] = $memberInfo['level'];
			}
			$ret = $this->memberdb -> where(array('id' => $memberInfo['id'])) -> data($data) -> save();//dump($ret);
			if($ret != 0 && $memberInfo['level'] < $data['level']){
				//升级，算回会员以前的佣金
				$db = M('Member_account_log');
				$db -> where(array('member_id' => $memberInfo['id'], 'pdstate' => 100)) -> data(array('pdstate' => 3)) -> save();
				sendWXMsg($memberInfo['openid'], str_replace('@levelname@', $this->getLevelName(), $affsettingarr['changelevel']));
			}
			//echo $this->memberdb -> getLastSql();
			$mtmdb = M('Member_member');
			$mtmdb -> where(array('smember_id' => $memberInfo['id'])) -> data($data) -> save();
		//}
	}
	
	//获取等级名称
	public function getLevelName(){
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$namelist = $this -> affsettingarr['levelname'];
		$namelist[] = $this -> affsettingarr['levelnamebase'];
		$namelist[] = '普通会员';
		$namelist = array_reverse($namelist);
		return $namelist[$memberInfo['level']];
	}
	
	//获取等级名称列表
	public function getLevelNameList(){
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$namelist = $this -> affsettingarr['levelname'];
		$namelist[] = $this -> affsettingarr['levelnamebase'];
		$namelist[] = '普通会员';
		$namelist = array_reverse($namelist);
		return $namelist;
	}
	
	//获取父子级会员数组8级
	public function getUserArr($pid=0,$arr=array(), $deep = 0){
		$re=$this->memberdb->where(array('id'=>$pid,'site_id'=>$this->site_id))->find();
		if($_GET['dump']){dump($this -> affsettingarr['VIPaff']);}
			if($this -> affsettingarr['VIPaff'] == 1 && $deep == 0){
				$member = $this->memberdb -> where(array('id'=>$this->member_id,'site_id'=>$this->site_id)) -> find();
				
				if($member['level'] > 0){
					$re = $member;
				}
			}
		//8级返回
		if($deep == 8){return $arr;}
		if(!is_array($re)){
			return $arr;
		}else{
			$re['deep'] = $deep + 1;
			//if($re['level'] > 0){
			    $arr[]=$re;
			//}
			$deep ++;
			return $this->getUserArr($re['pid'],$arr, $deep);
		}
	}
	
	//获取父子级会员数组无限级
	public function getUserArrAll($pid=0,$arr=array(), $deep = 0){
		$re=$this->memberdb->where(array('id'=>$pid,'site_id'=>$this->site_id))->find();
		if(!is_array($re)){
			return $arr;
		}else{
			if($re['level'] > 1){
				$re['deep'] = $deep + 1;
			    $arr[]=$re;
			}
			$deep ++;
			
			
			return $this->getUserArrAll($re['pid'],$arr, $deep);
		}
	}
	
	
	
	
	//获取VIP分成用户列表(需要分成的用户列表)
	public function getuserlist(){
		$ordermember = $this->memberdb -> where(array('id' => $this->order['member_id'])) -> find();
		
		$affsettingarr = $this -> affsettingarr;
		
		$list = $this -> getUserArr($ordermember['pid']);
		
		foreach($list as $k => $v){
			if($affsettingarr['VIPaff'] == 1 && $ordermember['level'] > 0 && $k == 0){
				$list[$k]['aff'] = $affsettingarr['level'][$k];
				continue;
			}
			if($v['level'] > 0){
			    $list[$k]['aff'] = $affsettingarr['level'][$k];
				$list[$k]['aff__'] = 0;
			}else{
				$list[$k]['aff'] = 0;
				$list[$k]['aff__'] = $affsettingarr['level'][$k];
			}
		}
		return $list;
	}
	
	//获取总代分成总额
	public function getuserlistAll(){
		$ret = array();
		$ordermember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$list = $this -> getUserArrAll($ordermember['pid']);
		$affList = array_reverse($this->affsettingarr['rlevel']);//dump($affList);
		foreach($list as $k => $v){
			
			if($k == 0){
				$aff = $affList[$v['level']-2];
			}else{
				$aff = $affList[$v['level']-2] - $affList[$list[$k - 1]['level']-2];
			}
			if($aff > 0){
			    $list[$k]['aff'] = $aff;
				
				$ret[] = $list[$k];
			}
			//$list[$k]['aff'] = $affList[$v['level']-2];
		}
		return $ret;
	}
	
	
	//下单提醒（当前未付款）
	public function sendMsg(){
		
		$thismember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		
		
		$db = M('Affiliatelog');
		$productList = $this->getmoney();
		$userList = $this->getuserlistAll();
		$userList1 = $this->getuserlist();
		$domain = C('DOMAIN_MAIN');
		$picurl = 'http://'.$domain[0].'/Public'.M('Product') -> where(array('id' => $productList[0]['product_id'])) -> getField('img_url');
		//往上发送信息
		foreach($userList as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				$map['type'] = 1;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id'];
				$map['product_id'] = $val['product_id'];
				if($db -> where($map) -> find()){
					continue;
				}
				
				
				//写入日志，以便以后统计，注意这里不是写账户日志
				$data['site_id'] = $this->order['site_id'];
				$data['member_id'] = $v['id'];
				$data['datetime'] = time();
				$data['type'] = 1;
				$data['order_id'] = $this->order['id'];
				$data['aff_money'] = round($val['aff_money']*$v['aff']/100,2);
				$data['product_id'] = $val['product_id'];
				if($data['aff_money'] > 0){
					$money += $data['aff_money'];
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$sendWXNews[0]['title'] = '会员下单通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，会员付款后您将得到分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
		
		foreach($userList1 as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				$map['type'] = 0;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id']; 
				$map['product_id'] = $val['product_id'];
				if($db -> where($map) -> find()){
					continue;
				}
				//写入日志，以便以后统计，注意这里不是写账户日志
				$data['site_id'] = $this->order['site_id'];
				$data['member_id'] = $v['id'];
				$data['datetime'] = time();
				$data['order_id'] = $this->order['id'];
				$data['aff_money'] = round($val['aff_money']*$v['aff']/100,2);
				$data['product_id'] = $val['product_id'];
				if($data['aff_money'] > 0){
					$money += $data['aff_money'];
					$db -> data($data) -> add();
				}
			}
			if($money > 0){ 
				//信息通知
				$sendWXNews[0]['title'] = '会员下单通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，会员付款后您将得到分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}else{
				$sendWXNews[0]['title'] = '会员下单通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'];
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
	}
	
	//写入分成日志
	
	public function insertlogAll(){
		
		
		
		
		
		
		
		$thismember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$db = M('Member_account_log');
		$productList = $this->getmoney();
		$userList = $this->getuserlistAll();
		$domain = C('DOMAIN_MAIN');
		$picurl = 'http://'.$domain[0].'/Public'.M('Product') -> where(array('id' => $productList[0]['product_id'])) -> getField('img_url');
		foreach($userList as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				
				$map['type'] = 1;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id'];
				$map['product_id'] = $val['product_id'];
				$map['attr'] = $val['attr'];
				if($db -> where($map) -> find()){
					continue;
				}
				
				
				$data['type'] = 1;
				$data['member_id'] = $v['id'];
				$data['user_id'] = 0;
				$data['pdstate'] = 3; //类型3为分成
				$data['dateline'] = time();
				
				$data['deep'] = $v['deep'];
				$data['affmoney'] = $val['aff_money'];
				
				$data['changenum'] = round($val['aff_money']*$v['aff']/100,2);
				$data['order_id'] = $this->order['id'];
				$data['order_sn'] = $this->order['ordernumber'];
				$data['product_id'] = $val['product_id'];
				$data['num'] = $val['num'];
				$data['site_id'] = $this->site_id;
				$data['attr'] = $val['attr'];
				$data['remark'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$data['changenum'];
				$data['goodsMoney'] = $val['total'];
				if($data['changenum'] > 0){
					$money += $data['changenum'];
					
					//是否需要审核分成
					$flag = false;
					if($val['affpass'] > 0){
						$hbcount = ceil($data['changenum'] / 200);
						$hbmoney = $data['changenum'];
						for($i = 0; $i < $hbcount; $i++){
							$sendmoney = 200;
							if($hbmoney > 200){
							    $hbmoney = $hbmoney - 200;
							}else{
								$sendmoney = $hbmoney;
							}
							//dump($sendmoney);
							$result = sendBonus($v['openid'],$sendmoney,$this->site_id);
						}
						//exit;
					}
					
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$sendWXNews[0]['title'] = '订单支付通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				//$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
	}
	
	
	public function insertlog(){
		$thismember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		
		
		$db = M('Affiliatelog');
		$db -> where(array('order_id' => $this->order['id'])) -> delete();
		
		
		
		$db = M('Member_account_log');
		$productList = $this->getmoney();
		$userList = $this->getuserlist();
		$domain = C('DOMAIN_MAIN');
		$picurl = 'http://'.$domain[0].'/Public'.M('Product') -> where(array('id' => $productList[0]['product_id'])) -> getField('img_url');
		foreach($userList as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				
				$map['type'] = 0;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id'];
				$map['product_id'] = $val['product_id'];
				$map['attr'] = $val['attr'];
				if($db -> where($map) -> find()){
					continue;
				}
				
				
				$data['deep'] = $v['deep'];
				$data['affmoney'] = $val['aff_money'];
				
				$data['type'] = 0;
				$data['member_id'] = $v['id'];
				$data['user_id'] = 0;
				$data['pdstate'] = 3; //类型3为分成
				if($v['aff__'] > 0){
					//未确认分成
					$data['pdstate'] = 100;
				}
				$data['dateline'] = time();
				$data['changenum'] = round($val['aff_money']*$v['aff']/100,2);
				$data['order_id'] = $this->order['id'];
				$data['order_sn'] = $this->order['ordernumber'];
				$data['product_id'] = $val['product_id'];
				$data['num'] = $val['num'];
				$data['site_id'] = $this->site_id;
				$data['attr'] = $val['attr'];
				$data['remark'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$data['changenum'];
				$data['goodsMoney'] = $val['total'];
				if($data['changenum'] > 0){
					$money += $data['changenum'];
					//是否需要审核分成
					$flag = false;
					if($val['affpass'] > 0){
						$hbcount = ceil($data['changenum'] / 200);
						$hbmoney = $data['changenum'];
						for($i = 0; $i < $hbcount; $i++){
							$sendmoney = 200;
							if($hbmoney > 200){
							    $hbmoney = $hbmoney - 200;
							}else{
								$sendmoney = $hbmoney;
							}
							//dump($sendmoney);
							$result = sendBonus($v['openid'],$sendmoney,$this->site_id);
						}
						//exit;
					}
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$sendWXNews[0]['title'] = '订单支付通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				//$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
		//总代分成写入
		$this->insertlogAll();
	}
	
	//撤消一个分成
	public function loggoback(){
		
	}
	
	//获取分成总额
	public function getmoney(){
		return $this -> saledb -> where(array('order_id' => $this->order['id'])) -> Field('(aff_money*num) as aff_money,product_id,total,num,attr,affpass,site_id') -> select();
	}
	
	//返回错误信息
	public function getError(){
		return $this->error['info'];
	}
	
	
	public function getAffData(){
		$db = M('Member_account_log');
		$levelname = $this -> getLevelName();
		
		
		$level = M('Member') -> where(array('id' => $this->member_id)) -> getField('level');
		//if(isset($_GET['dump'])){echo $level;dump($this->member_id);}
		$ret = array();
		if($level > 1){ 
			
		    $data = $db -> where(array('member_id' => $this->member_id, 'site_id' => $this->site_id, 'type' => 1, 'pdstate' => 3, 'order_id' => array('gt',0))) -> Field('count(*) as orderCount, sum(changenum) as orderAffMoney, sum(goodsMoney) as orderTotal') -> select();
			//dump($db -> getLastSql());
			$ret[0]['levelname'] = $levelname;
			//级差订单数量
			$ret[0]['orderCount'] = (int)$data[0]['orderCount'];
			//级差订单总额
			$ret[0]['orderTotal'] = (float)$data[0]['orderTotal'];
			//级差订单分成
			$ret[0]['orderAffMoney'] = (float)$data[0]['orderAffMoney'];
			
			$ret[0]['type'] = 1; 
		}
		
		 
		if($level > 0){
			$data = $db -> where(array('member_id' => $this->member_id, 'site_id' => $this->site_id, 'type' => 0, 'pdstate' => 3, 'order_id' => array('gt',0))) -> Field('count(*) as orderCount, sum(changenum) as orderAffMoney, sum(goodsMoney) as orderTotal') -> select();
			
			$ret[1]['levelname'] = $this -> affsettingarr['levelnamebase'];
			//VIP订单数量
			$ret[1]['orderCount'] = (int)$data[0]['orderCount'];
			//VIP订单总额
			$ret[1]['orderTotal'] = (float)$data[0]['orderTotal'];
			//VIP订单分成
			$ret[1]['orderAffMoney'] = (float)$data[0]['orderAffMoney'];
			$ret[1]['type'] = 0;
		}
		return $ret;
	}
	
}